<?php
/**
 * Created by b17
 * 2/22/12 8:50 PM
 */

namespace Managers\Builder;

class NewsBuilder
{
    private $_dateFormat = 'm/d/Y';

    /**
     * @var \Doctrine\ORM\QueryBuilder
     */
    protected $qb;

    public function __construct()
    {
        $this->reset();
    }

    public function reset()
    {
        $manager = new \Managers\News();
        $this->qb = $manager->createBaseQueryBuilder();
    }

    public function setRubric($rubricId)
    {
        $this->qb->andWhere('r.id = :rubric')->setParameter('rubric', $rubricId);
        return $this;
    }

    public function setIssue($issueId)
    {
        $this->qb->andWhere('i.id = :issue')->setParameter('issue', $issueId);
        return $this;
    }

    public function setId($id)
    {
        $this->qb->andWhere('n.id = :id')->setParameter('id', $id);
        return $this;
    }

    public function setIds(array $ids)
    {
        $this->qb->andWhere($this->qb->expr()->in('n.id', $ids));
        return $this;
    }

    public function setAllowComments($flag = true)
    {
        $this->qb->andWhere('n.allowComments = :cmnts')->setParameter('cmnts', (int)$flag);
    }

    public function setLimit($limit, $offset = 0)
    {
        $this->qb->setMaxResults($limit)
            ->setFirstResult($offset);
        return $this;
    }

    public function getTotal()
    {
        $qb = clone $this->qb;
        $qb->select('count(n.id) as total');
        $res = $qb->getQuery()->getArrayResult();
        return $res[0]['total'];
    }

    public function getList()
    {
        $res = $this->qb->getQuery()->getArrayResult();
        return $res;
    }

    public function getOne()
    {
        $res = $this->qb->getQuery()->getArrayResult();
        return count($res) ? $res[0] : false;
    }

    public function setDateStart($start)
    {
        if (is_string($start)) {
            $start = $this->_createDateTime($start);
        }
        if ($start instanceof \DateTime) {
            $this->qb->andWhere('n.date > :start')->setParameter('start', $start);
        }
        return $this;
    }

    public function setDateEnd($end)
    {
        if (is_string($end)) {
            $end = $this->_createDateTime($end);
        }
        if ($end instanceof \DateTime) {
            $this->qb->andWhere('n.date < :end')->setParameter('end', $end);
        }
        return $this;
    }

    private function _createDateTime($timeString)
    {
        return \DateTime::createFromFormat($this->_dateFormat, $timeString);
    }

    public function addOrderByViews($order = 'DESC')
    {
        $this->qb->addOrderBy('n.views', $order);
        return $this;
    }
}
